﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ZGRemote.Common.Builder;

namespace ZGRemote.Server.UI.ViewModels
{
    public partial class BuilderViewModel : ViewModelBase
    {
        [ObservableProperty]
        private string serverIP;

        [ObservableProperty]
        private string serverPort;

        [ObservableProperty]
        private string clientTag;

        [ObservableProperty]
        private Guid mutex;

        public BuilderViewModel()
        {
            serverIP = "127.0.0.1";
            serverPort = "9527";
            clientTag = "debugc";
            mutex = Guid.NewGuid();
            header = Core.Properties.Resources.Builder;
        }

        [RelayCommand]
        private void RefreshMutex()
        {
            Mutex = Guid.NewGuid();
        }

        [RelayCommand]
        private void BuildClient()
        {
            string binPath = Path.Combine(SettingConfig.PROGRAM_DIRECTORY, SettingConfig.Settings.ClientBin);
            
            
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = $"{Core.Properties.Resources.Executable} (*.exe)|*.exe";
            saveFileDialog.DefaultExt = ".exe";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            saveFileDialog.FileName = "client.exe";
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                File.Copy(binPath, filePath);
                var rsa = new RSACryptoServiceProvider();
                rsa.ImportCspBlob(SettingConfig.RSACSPBLOB);
                var data = new BuilderData()
                {
                    ServerIP = ServerIP,
                    ServerPort = int.Parse(ServerPort),
                    Tag = ClientTag,
                    MUTEX = Mutex.ToString(),
                    RSACSPBLOB = rsa.ExportCspBlob(false)
                };
                Builder.SaveData(filePath, data);
               
                Growl.Success($"{Core.Properties.Resources.BuildClientSuccess}\n{filePath}");
            }
        }
    }
}
